package com.xhh.greymall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xhh.common.utils.OkHttpUtils;
import com.xhh.common.utils.R;
import com.xhh.greymall.auth.feign.MemberFeignService;
import com.xhh.common.vo.MemberRespVo;
import com.xhh.greymall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 处理社交登录请求
 * @author: wei-xhh
 * @create: 2020-07-21
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws IOException {

        Map<String,String> map = new HashMap<>();
        map.put("client_id","1799353902");
        map.put("client_secret","4111ba9026c164e1447a7254a650be2e");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.greymall.com/oauth2.0/weibo/success");
        map.put("code",code);

        //1、根据code换取accessToken
        Response response = OkHttpUtils.doPost("api.weibo.com", "/oauth2/access_token", map);
        if(response.code() == 200){
            assert response.body() != null;
            String json = response.body().string();
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道了当前是哪个社交用户
            //1、当前用户如果第一次进网站，自动注册（为当前社交用户生成一个会员信息账号）
            //判断登录或者注册
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if(oauthLogin.getCode() == 0){
                MemberRespVo data = oauthLogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登录成功：用户 {}", data.toString());
                //1、第一次使用session:命令浏览器保存 JSESSIONID这个cookie;
                //以后浏览器访问哪个网站就会带上这个网站的cookie;
                //子域之间：greymall.com,auth.greymall.com
                //保存session（指定域名为父域名）时，子域保存，父域也可以拿到
                //SpringSession使用了拦截器
                //TODO 1、默认发的令牌 修改作用域
                //TODO 2、使用JSON的序列化方式来序列化对象
                session.setAttribute("loginUser",data);
                //登录成功
                return "redirect:http://greymall.com";

            } else {
                return "redirect:http://auth.greymall.com/login.html";
            }
        } else {
            return "redirect:http://auth.greymall.com/login.html";
        }
    }
}
